/*
 * @Author: wangqizhang
 * @Date: 2024-04-26 15:28:21
 * @LastEditors: wangqizhang
 * @LastEditTime: 2024-05-02 16:29:20
 * @FilePath: /suixinji-server/service/user.service.js
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */

const { User } = require('../model/user.model');
const { generateToken } = require('../until');
const { initSqlTask, runSqlTask } = require('.');
const bcrypt = require('bcrypt');

class UserService {
  async createUser(user) {
    try {
      //密码加密
      const res = await runSqlTask(initSqlTask(User, 'create', user));
      return res;
    } catch (error) {
      return error;
    }
  }
  async getUserInfoByUserName(user_name) {
    try {
      const res = await runSqlTask(initSqlTask(User, 'findOne', { user_name }));
      return res;
    } catch (error) {
      return error;
    }
  }
  async updateUser(id, userInfo) {
    try {
      const res = await runSqlTask(
        initSqlTask(User, 'update', { id, userInfo })
      );
      return res;
    } catch (error) {
      return error;
    }
  }
  async deleteUser(id) {
    try {
      const res = await runSqlTask(initSqlTask(User, 'delete', { id }));
      return res;
    } catch (error) {
      return error;
    }
  }
  async userlogin(userInfo) {
    const { user_name, pass_word } = userInfo;
    const finds = await runSqlTask(initSqlTask(User, 'findOne', { user_name }));

    if (finds.status && finds.result !== null) {
      const compareResult = await bcrypt.compare(
        pass_word,
        finds.result.pass_word
      );
      if (compareResult) {
        //生成token
        const token = await generateToken(finds.result);
        return {
          status: true,
          result: {
            token: token,
          },
        };
      } else {
        return {
          status: false,
          result: '密码错误',
        };
      }
    }
  }
}
module.exports = new UserService();
